package com.gnerv.tools.entity.extend.utils.mapper;

import com.gnerv.tools.entity.extend.annotation.EntityExtend;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMapping;

import java.util.ArrayList;
import java.util.List;

public class CompositesUtils {

    private CompositesUtils() {
    }

    public static List<ResultMapping> buildHashComposites(MappedStatement ms, EntityExtend entityExtend) {
        List<ResultMapping> lists = buildHashComposites(ms, Object.class, entityExtend);
        return lists;
    }

    public static List<ResultMapping> buildHashComposites(MappedStatement ms, Class<?> javaType, EntityExtend entityExtend) {
        List<ResultMapping> lists = new ArrayList<>(10);
        String column = entityExtend.column();
        String replace = column.replace("{", "").replace("}", "");
        String[] split = replace.split(",");
        for (String str : split) {
            ResultMapping resultMapping;
            String[] strings = str.split("=");
            if (strings.length == 1) {
                resultMapping = new ResultMapping.Builder(ms.getConfiguration(), strings[0], strings[0], javaType)
                        .nestedQueryId(null)
                        .build();
            } else if (strings.length == 2) {
                resultMapping = new ResultMapping.Builder(ms.getConfiguration(), strings[0], strings[1], javaType)
                        .nestedQueryId(null)
                        .build();
            } else {
                throw new RuntimeException("参数异常！" + column);
            }
            lists.add(resultMapping);
        }
        return lists;
    }

    public static List<ResultMapping> buildExtendComposites(MappedStatement ms, EntityExtend entityExtend) {
        List<ResultMapping> lists = buildHashComposites(ms, Object.class, entityExtend);
        return lists;
    }

}
